package model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Route {
	private List<Road> route = new ArrayList<Road>();
	private Junction lastJunction;

	public Route(Junction start){
		this.lastJunction = start;
	}
	
	private Route(List<Road> route, Junction last){
		this.route.addAll(route);
		this.lastJunction = last;

		assert last == null || getLast() == null || getLast().isConnectedTo(last) : "Last road is not connected to last junction"; 
	}

	public Route copy(){
		return new Route(this.route, lastJunction);
	}

	public void add(Road r){
		assert !route.contains(r) : "Route already contains junction"; 

		if(getLast() == null || getLast().isConnectedTo(r)){
			assert r.isConnectedTo(lastJunction);
			if(r.getSideA() == lastJunction)
				lastJunction = r.getSideB();
			else
				lastJunction = r.getSideA();

			route.add(r);
		}
		else
			assert false : ("Failed to add Road. Road \"" + getLast() + "\" is not connected to \"" + r + "\"");
	}

	public Road getLast(){
		if(route.size() > 0)
			return route.get(route.size()- 1);
		else
			return null;
	}

	public String toString(){
		StringBuilder b = new StringBuilder();
		Iterator<Road> itt = route.iterator();

		assert itt.hasNext() : "Need to display an empty route?";
		b.append("[");
		while(itt.hasNext()){
			Road r = itt.next();
			b.append(r);
			b.append(",");
		}
		b.deleteCharAt(b.length()-1);
		b.append("]");
		return b.toString();
	}

	public Junction getLastJunction() {
		if(route.isEmpty())
			return null;
		return lastJunction;
	}

	public boolean contains(Road r) {
		return route.contains(r);
	}

	public void setStart(Junction start) {
		lastJunction = start;
	}
	
	public double getLength(){
		double length = 0;
		for (Road r : route) {
			length += r.getLength();
		}
		return length;
	}
	
	public void addPlayers(double amount) {
		double totalLength = getLength();
		for (Road r : route) {
			double nrOfPlayers = amount * r.getLength() / totalLength;
			r.addVehicles(nrOfPlayers);
		}
	}

	public double getTravelTime() {
		double travelTime = 0;
		for (Road r : route) {
			travelTime += r.getTravelTime();
		}
		return travelTime;
	}
}
